package com.jiuyuejiu.func_pic;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.android.material.appbar.AppBarLayout;
import com.jiuyuejiu.R;
import com.jiuyuejiu.application.ConstValues;
import com.jiuyuejiu.base.BaseActivity;
import com.jiuyuejiu.domain.HomePicStc;
import com.jiuyuejiu.func_pic.adapter.LocalPicTypeAdapter;
import com.jiuyuejiu.func_video.VideoService;
import com.jiuyuejiu.func_video.domain.VideoFenleiStc;
import com.jiuyuejiu.utils.ShanHaiUtil;
import com.kylin.core.banner.BannerCreator;
import com.kylin.core.utils.dbtutil.FileUtil;
import com.kylin.core.utils.dbtutil.FunUtil;
import com.kylin.core.utils.dbtutil.JsonUtil;
import com.kylin.core.utils.flyn.Eyes;
import com.kylin.core.view.NoScrollListView;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.widget.NestedScrollView;


public class LocalPicTypeActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "LocalPicTypeActivity";

    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private AppCompatTextView backTv;
    private AppCompatTextView titleTv;

    private AppBarLayout app_bar;
    private NestedScrollView nestedscrollview;

    ConvenientBanner<String> convenientBanner;

    // 获取从上一页传递过来的数据
    private String title;
    // private String password;

    private NoScrollListView dataLv;
    private LinearLayout emptyLl;

    // 原画类型集合
    private List<VideoFenleiStc> picTypeList = new ArrayList<>();
    private LocalPicTypeAdapter localPicTypeAdapter;

    // 轮播图列表
    private ArrayList<String> bannerPics;

    MyHandler handler;
    private PicService service;
    private VideoService videoService;

    // 文件的MD5名称
    private String fileName;


    /**
     * 接收子线程消息的 Handler
     */
    public class MyHandler extends Handler {

        // 软引用
        SoftReference<LocalPicTypeActivity> fragmentRef;

        public MyHandler(LocalPicTypeActivity fragment) {
            fragmentRef = new SoftReference<LocalPicTypeActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            LocalPicTypeActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }

            Bundle bundle = msg.getData();
            super.handleMessage(msg);
            // 处理UI 变化
            switch (msg.what) {
                // 提示信息
                case ConstValues.WAIT0:// 加载网络获取Banner的回调
                    fragment.getBannerPicListSuc(bundle);
                    break;
                case ConstValues.WAIT1:// 获取所有图片类型的回调
                    fragment.getPicTypeListSuc(bundle);
                    break;

                default:
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic);

        // 标题栏白底黑字
        Eyes.setStatusBarLightMode(this, Color.WHITE);

        // 接收传递过来的参数
        initCreate();
        // 初始化视图
        initView();
        // 初始化数据
        initData();


    }

    private void initCreate() {

        /*// 上一页面设置数据
        Intent intent = null;
        intent = new Intent(this, RePwdActivity.class);
        Bundle bundl = new Bundle();
        intent.putExtra("username", "");
        intent.putExtra("password", "");
        startActivity(intent);*/

        // 本页面获取数据
        // Intent i = getIntent();
        // username = (String) i.getSerializableExtra("username");
        // password = (String) i.getSerializableExtra("password");
    }

    private void initView() {

        backBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.top_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_confirm);
        backTv = (AppCompatTextView) findViewById(R.id.top_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.top_navigation_tv_title);
        confirmBtn.setVisibility(View.INVISIBLE);
        confirmBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);

        app_bar = (AppBarLayout) findViewById(R.id.yd_datacolect_amend_app_bar);
        nestedscrollview = (NestedScrollView) findViewById(R.id.yd_datacolect_nestedscrollview);

        convenientBanner = (ConvenientBanner<String>) findViewById(R.id.yd_fir_banner_recycler_item);

        emptyLl = (LinearLayout) findViewById(R.id.pic_ll_empty);
        dataLv = (NoScrollListView) findViewById(R.id.pic_ll_list);

    }

    private void initData() {
        handler = new MyHandler(this);
        service = new PicService(LocalPicTypeActivity.this, handler);
        videoService = new VideoService(LocalPicTypeActivity.this, handler);

        // 获取上一页传递过来的数据
        Intent i = getIntent();
        title = i.getStringExtra("title");

        titleTv.setText(title);




        dataLv.setEmptyView(emptyLl);

        app_bar.setVisibility(View.VISIBLE);
        nestedscrollview.setVisibility(View.VISIBLE);

        localPicTypeAdapter = new LocalPicTypeAdapter(LocalPicTypeActivity.this, picTypeList);
        dataLv.setAdapter(localPicTypeAdapter);

        // 点击查看
        dataLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                VideoFenleiStc picType = picTypeList.get(position);
                Intent picI = new Intent(LocalPicTypeActivity.this, LocalPicListActivity.class);
                picI.putExtra("picType", picType);//
                startActivity(picI);

            }
        });

        // 获取轮播图Banner
        service.getBannerPicList(ConstValues.PIC_JSON_BANNER);

        // 获取所有图片类型
        fileName = FunUtil.StringToMd5(ConstValues.PICNAME);
        FileUtil.deleteFile(new File(ShanHaiUtil.parseFilePath(fileName)));// 先删除
        String downurl = ShanHaiUtil.getHttpid() + ConstValues.PICPATH + ConstValues.TXTNAME;
        // 请求
        videoService.downCatVideoJsonList(downurl,// 请求url
                fileName, // 本地存储名称
                true, // 是否显示进度条 false不显示下载进度,true显示下载进度框
                ConstValues.WAIT1);// 用于当前Activity界面handle的对应回调接收 比如what1,what2

    }

    // 获取轮播图Banner的回调
    private void getBannerPicListSuc(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {

            ArrayList<HomePicStc> homePicStcs = (ArrayList<HomePicStc>) JsonUtil.parseList(formjson, HomePicStc.class);

            bannerPics = new ArrayList<>();
            for (HomePicStc banner : homePicStcs) {
                bannerPics.add(banner.getImageurl());
            }
            BannerCreator.setDefault(convenientBanner, bannerPics, new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    // 条目点击监听
                    // Toast.makeText(_mActivity, "点击了第" + position + "项", Toast.LENGTH_SHORT).show();
                }
            });

        } else {
            Toast.makeText(LocalPicTypeActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }

    // 获取所有图片类型的回调
    private void getPicTypeListSuc(Bundle bundle) {
        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {
            String pdfpath = ShanHaiUtil.parseFilePath(fileName);// 拼接文件路径
            File docFile = new File(pdfpath);
            if (docFile.exists()) {//存在本地;
                try {
                    // 传入File文件 读取文件内容
                    String result = ShanHaiUtil.parseFileToString(docFile);
                    // 传入字符串 将字符串分割成数组
                    String[] read = ShanHaiUtil.splitStringToArray(result);
                    // 将数组 转成 集合
                    ArrayList<VideoFenleiStc> detailStcs = ShanHaiUtil.parseStringArrayToList(read);

                    picTypeList.clear();
                    picTypeList.addAll(detailStcs);

                    localPicTypeAdapter.notifyDataSetChanged();

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(LocalPicTypeActivity.this, "没有找到视频文件", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(LocalPicTypeActivity.this, "没有找到分类文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(LocalPicTypeActivity.this, formjson, Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 返回
            case R.id.top_navigation_rl_back:
                this.finish();
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        // 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
        super.onBackPressedSupport();
        this.finish();
    }
}
